// 云函数入口文件
const cloud = require('wx-server-sdk')
const TcbRouter = require('tcb-router');

cloud.init()
const db = cloud.database();
const dbBlogCollection = db.collection("blog2");
const MAX_LIMIT = 100;

// 云函数入口函数
exports.main = async(event, context) => {
  const app = new TcbRouter({
    event
  });

  app.router("getBlogList", async(ctx, next) => {
    const countResult = dbBlogCollection.count();
    const total = countResult.total;

    // 模糊搜索
    let keyword = event.keyWord;
    let w = {};
    if (keyword != "") {
      w = {
        content: db.RegExp({
          regexp: keyword,
          options: "i"
        })
      }
    }

    ctx.body = await dbBlogCollection
      .where(w)
      .skip(event.start)
      .limit(event.count)
      .orderBy("createTime", "desc")
      .get()
      .then((res) => {
        return {
          total,
          data: res.data
        }
      });


  });

  app.router("detail", async(ctx, next) => {
    let blogId = event.blogId;
    let detail = await dbBlogCollection
      .where({
        _id: blogId
      })
      .get()
      .then((res) => {
        return res.data
      })

    
    // 评论查询
    const countResult = await db.collection("blog-comment2").where({ blogId }).count(); // 查询的总数
    const total = countResult.total;
    // 评论的结果
    let commentList = {
      data: []
    };

    if (total > 0) {
      // 计算出通过几次把结果查询到
      const batchTimes = Math.ceil(total / MAX_LIMIT);
      const tasks = [];
      for (let i = 0; i < batchTimes; i++) {
        let promise = db.collection('blog-comment2').skip(i * MAX_LIMIT)
          .limit(MAX_LIMIT)
          .where({
            blogId
          })
          .orderBy('createTime', 'desc')
          .get()
        tasks.push(promise)
      }
      if (tasks.length > 0) {
        // 把结果累加到当前的结果上
        commentList = (await Promise.all(tasks)).reduce((acc, cur) => {
          return {
            data: acc.data.concat(cur.data)
          }
        })
      }
    }

    ctx.body = {
      detail,
      commentList
    }

  });

  app.router("getListByOpenid", async(ctx, next) => {
    const wxContext = cloud.getWXContext();
    const countResult = await dbBlogCollection.where({ _openid: wxContext.OPENID}).count();
    const total = countResult.total;

    ctx.body = await dbBlogCollection
      .where({
        _openid: wxContext.OPENID
      })
      .skip(event.start)
      .limit(event.count)
      .orderBy("createTime", "desc")
      .get()
      .then((res) => {
        return {
          total,
          data: res.data
        }
      });
  });

  
  return app.serve();
}